package com.binance.notification.web.health;

import com.binance.notification.web.controller.JController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * @author wangxiao
 */
@Component
@Slf4j
public class BusinessHealthIndicator implements HealthIndicator {

    @Autowired
    private JController jController;
    @Autowired
    private RestTemplate restTemplate;
    @Value("${server.port}")
    private int port;

    @Override
    public Health health() {
        Health.Builder builder = new Health.Builder();
        String ip = System.getProperty("local-ip");
        String url = "http://" + ip + ":" + port + "/internal/apiurl";
        try {
            Map resp = restTemplate.getForObject(url, Map.class);
            if (resp == null) {
                return builder.down().build();
            }
            String status = resp.get("status").toString();
            if ("ERROR".equals(status)) {
                return builder.down().build();
            }
            if (resp.get("data") == null) {
                return builder.down().build();
            }
        } catch (Exception e) {
            log.warn("业务健康检查：", e);
            return builder.down().build();
        }
        return builder.up().build();
    }

}
